<template>
  <div class="kmSummary">
    <div class="clearfix searchBox">
      <div class="fl search">
        <quickSearch :advForm="quickSearchForm" @QuickSearch="searchFun"></quickSearch>
      </div>
      <div class="fr btn">
        <el-button size="mini" type="primary" @click="searchFun">查询</el-button>
        <el-button size="mini" @click="importDialog"
          v-if="limitArr.indexOf(importLimit) > -1">
          导入
        </el-button>
      </div>
    </div>
    <div class="knowledgeListBox">
      <knowledgeList :dirObj="currentDirObj"></knowledgeList>
    </div>
    <el-dialog
      title="导入常用语"
      :visible.sync="importVisible"
      width="30%">
      <div>
        <el-button size="mini" icon="el-icon-download" class="fl importBtn">
          <a href="/temp/cw-Import.xlsx" download="cw-import">下载导入模板</a>
        </el-button>
        <el-upload
          class="upload-demo"
          ref="epxortKm"
          accept=".xls, .xlsx"
          :action="kmUrl"
          :limit='1'
          :on-success="handleImportSuccess"
          :on-remove="handleRemove"
          :headers="{
            sessionid: accountObj.userId,
            loginToken: accountObj.loginToken
          }">
          <el-button size="mini" class="fl" style="marginLeft: 10px">导入Excel文件</el-button>
        </el-upload>
        <div class="instructions">
          <h5>说明：</h5>
          <ul>
            <li>1、支持后缀为xls何xlsx的excel文件导入；</li>
            <li>2、wps格式的文件导入成功率高，office低版本容易导入失败；</li>
            <li>3、支持一个文件一个工作表，多个工作表无法导入；</li>
            <li>4、一级类别下最多可创建50个子类别；</li>
            <li>5、每个类别下最多可创建100条常用语；</li>
            <li>6、模板表头不可修改，修改后无法导入；</li>
            <li>7、导入快捷回复词有50个字符限制，超过限制该条数据导入失败；</li>
            <li>8、导入内容只可以是单文本/url，其他内容导入失败；</li>
            <li>9、导入时异步处理，提交导入后可以立刻进行其他的导入，服务器会排队处理，结果在【传输中心】查看。</li>
          </ul>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
        <el-button type="primary" @click="importSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import knowledgeList from '@/views/km/knowledgeBase/knowledgeList.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { deepClone } from '@/utils/common'
import { KmModule } from '@/store/modules/km/index'
@Component({
  name: 'kmSummary',
  components: { knowledgeList, quickSearch }
})
export default class KmSummary extends Vue {
  private $bus: any
  private $message: any
  private $store: any
  private $router: any
  private $route: any
  private agentList = []

  private currentDirObj = {}

  private quickSearchForm: any = {
    form: {
      title: '',
      content: '',
      updateUser: ''
    },
    advSearchOptions: []
  }

  private accountObj = {
    account: '',
    userId: '',
    loginToken: ''
  }

  private importVisible = false

  private fileObj = {
    path: '',
    count: ''
  }

  private limitArr = []

  private importLimit = ''

  get kmUrl () {
    return '/upload?accountId=' + this.accountObj.account + '&module=km'
  }

  get importType () {
    return this.$route.path.split('/')[3]
  }

  private importDialog () {
    this.importVisible = true
  }

  private handleImportSuccess (res: any) {
    if (res && res.success) {
      this.fileObj.path = res.data.path
    }
  }

  private handleRemove () {
    this.fileObj.path = ''
  }

  private importSave () { //
    if (!this.fileObj.path) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/im-km/import/action/importQuickReplyTask',
      method: 'post',
      data: {
        type: this.importType === 'common_language' ? 'commonqr' : 'agentqr',
        filepath: this.fileObj.path
      }
    }
    const epxortRef: any = this.$refs.epxortKm
    epxortRef.clearFiles()
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('导入任务已经生成，请前往传输中心查看！')
        this.importVisible = false
      }
    })
  }

  private searchFun () {
    this.$bus.$emit('kmSearchFun', this.quickSearchForm.form)
  }

  private clearSearchForm () {
    this.quickSearchForm.form = {
      title: '',
      content: '',
      updateUser: ''
    }
  }

  private mounted () {
    if (this.importType === 'common_language') {
      this.quickSearchForm.advSearchOptions = [
        { label: '快捷词', inputType: 'input', name: 'title', clearable: true, placeholder: '请输入要搜索的快捷词' },
        { label: '常用语内容', inputType: 'input', name: 'content', clearable: true, placeholder: '请输入要搜索的信息' },
        { label: '最近更新人', inputType: 'select', name: 'updateUser', clearable: true, selectData: this.agentList }
      ]
    } else {
      this.quickSearchForm.advSearchOptions = [
        { label: '快捷词', inputType: 'input', name: 'title', clearable: true, placeholder: '请输入要搜索的快捷词' },
        { label: '常用语内容', inputType: 'input', name: 'content', clearable: true, placeholder: '请输入要搜索的信息' }
      ]
    }
    this.$bus.$on('directoryClick', (nodeObj) => {
      this.currentDirObj = (nodeObj && nodeObj.data) || {}
      this.clearSearchForm()
    })
    this.$bus.$on('searchListBack', () => {
      this.clearSearchForm()
    })
    this.$bus.$on('addKnowledge', () => {
      this.clearSearchForm()
    })
  }

  private beforeDestroy () {
    this.$bus.$off('directoryClick')
    this.$bus.$off('searchListBack')
    this.$bus.$off('addKnowledge')
  }

  private beforeMount () {
    const agents = deepClone(this.$store.state.common.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ _id: agents[i]._id, name: agents[i].name })
    }
    this.agentList = agentsArr
    this.limitArr = this.$store.state.common.session.user.functions // 权限处理
    const type = this.$route.path.split('/')[3]
    this.importLimit = type === 'common_language' ? 'import_common_language' : 'import_personal_language'
    this.accountObj.account = (this.$store as any).state.common.session.account._id
    this.accountObj.userId = (this.$store as any).state.common.session.user._id
    this.accountObj.loginToken = (this.$store as any).state.common.session.user.loginToken
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
  .kmSummary
    height 100%
    .searchBox
      height 90px
      overflow auto
      border-bottom 1px solid $border-main
      .search
        width calc(100% - 200px)
      .btn
        margin-top 25px
    .knowledgeListBox
      height calc(100% - 100px)
  .importBtn
    a
      color #303753
  .importBtn:hover a
    color #008cee
  .instructions
    margin-top 22px
    h5
      font-size 12
    li
      padding 4px
      color #767E91
      font-size 12px
</style>
<style lang="stylus">
  .el-cascader-node__label
    max-width 200px
</style>
